﻿using DataModels.Dto;
using DataModels.Dto.ShoppingMallDto;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.ShoppingMall;
using DataModels.Enums.ShoppingMall;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Utils;
using static DataModels.Enums.GeneralEnum;

namespace Services.ShoppingMall
{
    public class ShoppingMallService(SqlSugarClient db) : BaseService(db)
    {
        /// <summary>
        /// 获取商品分类列表
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetProductCategory()
        {
            var res = db.Queryable<ShoppingMallProductCategory>()
                .LeftJoin<ShoppingMallProductCategorySub>((smpc, smpcs) => smpc.UUID == smpcs.ShoppingMallProductCategoryUUID)
                .OrderBy((smpc, smpcs) => smpc.Sort)
                .OrderBy((smpc, smpcs) => smpcs.Sort)
                .Select((smpc, smpcs) => new
                {
                    CategoryId = smpc.UUID,
                    CategoryName = smpc.Name,
                    CategoryUrl = smpc.Url,
                    SubCategoryUrl = smpcs.Url,
                    SubCategoryId = smpcs == null ? Guid.Empty : smpcs.UUID,
                    SubCategoryName = smpcs == null ? "" : smpcs.Name
                })
                .ToList()
                .GroupBy(x => new { x.CategoryId, x.CategoryName, x.CategoryUrl })
                .Select(g => new
                {
                    UUID = g.Key.CategoryId,
                    Name = g.Key.CategoryName,
                    CategoryUrl = g.Key.CategoryUrl,
                    SubCategories = g.Select(x => new
                    {
                        UUID = x.SubCategoryId,
                        Name = x.SubCategoryName,
                        Url = x.SubCategoryUrl,
                    }).Where(sc => !string.IsNullOrEmpty(sc.Name)).ToList()
                })
                .ToList();

            return Success(res);
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> GetProduct(GetProductInfo info)
        {
            try
            {
                RefAsync<int> total = 0;
                // 分页查询商品基础信息
                List<GetProductDto> products = await db.Queryable<ShoppingMallProduct, ShoppingMallProductSpecification, ShoppingMallProductCategorySub>((smp, smps, smpc) => new JoinQueryInfos(
                     JoinType.Left, smp.UUID == smps.ShoppingMallProductUUID,
                     JoinType.Left, smp.ShoppingMallProductCategoryUUID == smpc.UUID
                     ))
                     .Where(smp => smp.IsDeleted == Status.Disable)
                     .Where(smp => smp.Status == Status.Enable)
                     // 大类
                     .WhereIF(info.CategoryUUID.HasValue, (smp, smps, smpc) => smpc.ShoppingMallProductCategoryUUID == info.CategoryUUID)
                     // 小类
                     .WhereIF(info.SubCategoryUUID.HasValue, smp => smp.ShoppingMallProductCategoryUUID == info.SubCategoryUUID)
                     // 推荐
                     .WhereIF(info.IsRecommend.HasValue, smp => smp.IsRecommend == info.IsRecommend)
                     // 搜索
                     .WhereIF(!string.IsNullOrEmpty(info.SearchWord), smp => smp.Title.Contains(info.SearchWord) || smp.Description.Contains(info.SearchWord))
                     // 店铺
                     .WhereIF(info.StoreUUID.HasValue, smp => smp.ShoppingMallStoreUUID == info.StoreUUID)
                     .GroupBy(smp => smp.UUID) // 按商品分组
                     .Select((smp, smps) => new GetProductDto
                     {
                         UUID = smp.UUID,
                         Title = smp.Title,
                         ImageUrl = smp.ImageUrl,
                         IsRecommend = smp.IsRecommend,
                         OriginalPrice = SqlFunc.AggregateMin(smps.OriginalPrice)
                     })
                     .ToPageListAsync(info.PageNumber, info.PageSize, total);

                if (products.Count == 0)
                {
                    return PageSuccess();
                }
                List<Guid> productsuuid = products.Select(p => p.UUID).ToList();
                // 获取订单量
                var orders = await db.Queryable<ShoppingMallOrder>()
                    .Where(smo => smo.IsDeleted == Status.Disable && productsuuid.Contains(smo.ShoppingMallProductUUID))
                    .GroupBy(smo => smo.ShoppingMallProductUUID)
                    .Select(smo => new
                    {
                        ProductUUID = smo.ShoppingMallProductUUID,
                        OrderCount = SqlFunc.AggregateCount(smo.UUID)
                    })
                    .ToListAsync();


                //获取商品最小规格价格（子查询）- 包括拼团价格
                var minPriceQuery = await db.Queryable<ShoppingMallProductSpecification, ShoppingMallProductGroupActivity>((smps, smpga) => new JoinQueryInfos(
                        JoinType.Left,
                        smps.ShoppingMallProductUUID == smpga.ShoppingMallProductUUID
                        && smpga.Status == Status.Enable
                        && smpga.IsDeleted == Status.Disable
                        && smpga.EndTime > DateTime.Now
                    ))
                    .Where(smps => smps.IsDeleted == Status.Disable && productsuuid.Contains(smps.ShoppingMallProductUUID))
                    .GroupBy(smps => smps.ShoppingMallProductUUID)
                    .Select((smps, smpga) => new
                    {
                        ProductUUID = smps.ShoppingMallProductUUID,
                        Specification = smps.UUID,
                        // 使用SqlFunc.IF判断是否有有效拼团价格
                        MinPrice = SqlFunc.AggregateMin(SqlFunc.IIF(smpga.UUID != Guid.Empty, smps.GroupPrice, smps.Price)),
                        IsGroup = SqlFunc.IIF(smpga.UUID != Guid.Empty, Status.Enable, Status.Disable)
                    })
                    .ToListAsync()
                    ;

                var minPrice = minPriceQuery.GroupBy(s => s.ProductUUID)
                    .Select(g => g.OrderBy(s => s.MinPrice).First())
                    .ToList();

                // 获取商品服务列表
                var productServices = await db.Queryable<ShoppingMallProductServiceMap>()
                    .LeftJoin<ShoppingMallProductService>((smpsm, smps) => smpsm.ShoppingMallProductServiceUUID == smps.UUID)
                    .Where((smpsm, smps) => productsuuid.Contains(smpsm.ShoppingMallProductUUID) && smpsm.Status == Status.Enable)
                    .Select((smpsm, smps) => new
                    {
                        ProductUUID = smpsm.ShoppingMallProductUUID,
                        ServiceName = smps.Name,
                        ServiceDescription = smps.Description
                    })
                    .ToListAsync();

                // 构建商品ID到服务列表的映射
                var serviceMap = productServices
                    .GroupBy(t => t.ProductUUID)
                    .ToDictionary(g => g.Key, g => g.Select(t => t.ServiceName).ToList());

                // 主查询
                foreach (var product in products)
                {
                    var mp = minPriceQuery.FirstOrDefault(mp => mp.ProductUUID == product.UUID);
                    product.Price = mp.MinPrice;
                    product.IsGroup = mp.IsGroup;
                    product.Services = serviceMap.TryGetValue(product.UUID, out List<string>? value) ? value : [];
                    product.OrderCount = orders.FirstOrDefault(o => o.ProductUUID == product.UUID)?.OrderCount ?? 0;
                }

                return PageSuccess(info.PageNumber, info.PageSize, total, products);
            }
            catch (Exception)
            {
                return Error("获取商品信息失败，请稍后再试！");
            }
        }

        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="ProductUUID"></param>
        /// <returns></returns>
        public async Task<ResponseModel> GetProductDetail(Guid ProductUUID)
        {
            try
            {
                // 分页查询商品基础信息
                GetProductDetailDto product = await db.Queryable<ShoppingMallProduct, ShoppingMallProductGroupActivity, ShoppingMallStore>((smp, smpga, sms) => new JoinQueryInfos(
                    JoinType.Left, smp.UUID == smpga.ShoppingMallProductUUID && smpga.EndTime > DateTime.Now,
                    JoinType.Left, smp.ShoppingMallStoreUUID == sms.UUID
                    ))
                    .Where(smp => smp.IsDeleted == Status.Disable)
                    .Where(smp => smp.Status == Status.Enable)
                    .Where(smp => smp.UUID == ProductUUID)
                    .Select((smp, smpga, sms) => new GetProductDetailDto
                    {
                        UUID = smp.UUID,
                        Title = smp.Title,
                        Subtitle = smp.Subtitle,
                        Description = smp.Description,
                        IsRecommend = smp.IsRecommend,
                        ImageUrl = smp.ImageUrl,
                        IsGroup = SqlFunc.IIF(smpga.UUID != Guid.Empty, Status.Enable, Status.Disable),
                        GroupEndTime = smpga.EndTime,
                        GroupCount = smpga.GroupCount,
                        MaxGroupCount = smpga.MaxGroupCount,
                        StoreUUID = sms.UUID,
                        StoreName = sms.Name
                    })
                    .FirstAsync()
                    ;

                if (product == null)
                {
                    return Error("指定商品已下架");
                }

                // 获取商品规格
                List<SpecificationDto> Specifications = await db.Queryable<ShoppingMallProductSpecification>()
                    .Where(s => s.IsDeleted == Status.Disable)
                    .Where(s => s.IsActive == Status.Enable)
                    .Where(s => s.ShoppingMallProductUUID == ProductUUID)
                    .Select(s => new SpecificationDto
                    {
                        SpecificationUUID = s.UUID,
                        Price = s.Price,
                        GroupPrice = s.GroupPrice,
                        OriginalPrice = s.OriginalPrice,
                        Name = s.Name,
                        Count = s.Count
                    })
                    .ToListAsync();

                // 获取订单量
                int ordercount = await db.Queryable<ShoppingMallOrder>()
                    .Where(smo => smo.IsDeleted == Status.Disable && product.UUID == smo.ShoppingMallProductUUID)
                    .GroupBy(smo => smo.ShoppingMallProductUUID)
                    .Select(smo => SqlFunc.AggregateCount(smo.UUID))
                    .FirstAsync();


                // 获取商品服务列表
                var productServices = await db.Queryable<ShoppingMallProductServiceMap>()
                    .LeftJoin<ShoppingMallProductService>((smpsm, smps) => smpsm.ShoppingMallProductServiceUUID == smps.UUID)
                    .Where((smpsm, smps) => product.UUID == smpsm.ShoppingMallProductUUID && smpsm.Status == Status.Enable)
                    .Select((smpsm, smps) => new ProductServices
                    {
                        UUID = smps.UUID,
                        Name = smps.Name,
                        Description = smps.Description
                    })
                    .ToListAsync();

                //获取评论数量和平均评分
                var orderServices = await db.Queryable<ShoppingMallOrderComment>()
                    .Where(smoc => smoc.IsDeleted == Status.Disable && smoc.ShoppingMallProductUUID == ProductUUID)
                    .GroupBy(smoc => smoc.ShoppingMallProductUUID)
                    .Select(smoc => new
                    {
                        ProductUUID = smoc.ShoppingMallProductUUID,
                        CommentCount = SqlFunc.AggregateCount(smoc.UUID),
                        AverageRating = SqlFunc.AggregateAvg((int)smoc.StarRating)
                    })
                    .FirstAsync();
                if (orderServices != null)
                {
                    product.CommentCount = orderServices.CommentCount;
                    product.AverageRating = orderServices.AverageRating;
                }

                product.ImageUrls = GetAttachment(product.UUID);
                product.OrderCount = ordercount;
                product.Services = productServices;
                product.Specifications = Specifications;
                return Success(product);
            }
            catch (Exception)
            {
                return Error("获取商品信息失败，请稍后再试！");
            }
        }

        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel> SubmitOrder(List<ShoppingMallSubmitOrderInfo> infos)
        {
            try
            {

                if (infos == null || infos.Count == 0)
                {
                    return Error("订单信息不能为空");
                }
                if (infos.Count == 0 && infos.Select(x => x.JoinGroup == Status.Enable).Count() > 1)
                {
                    return Error("拼团商品只能单独购买");
                }

                await db.BeginTranAsync();

                // 获取地址
                var da = await db.Queryable<DeliveryAddress>().Where(da => da.UUID == infos[0].AddressUUID).FirstAsync();
                if (da == null)
                {
                    await db.RollbackTranAsync();
                    return Error("地址不存在，请重新选择地址。");
                }
                ShoppingMallOrderTotal tt = new()
                {
                    OrderAmount = 0,
                    Address = da.AddressDetail,
                    ContactPerson = da.ContactPerson,
                    ContactPhone = da.ContactPhone,
                    CreateUserUUID = UserUUID,
                    CreateTime = DateTime.Now
                };
                ShoppingMallOrderTotal orderTotal = await db.Insertable(tt).ExecuteReturnEntityAsync();
                foreach (var info in infos)
                {
                    // 原子化更新库存并检查
                    int rowsAffected = await db.Ado.ExecuteCommandAsync(
                        @"UPDATE ShoppingMallProductSpecification 
              SET Count = Count - @Count, 
                  UpdateTime = @UpdateTime, 
                  UpdateUserUUID = @UpdateUserUUID 
              WHERE UUID = @UUID 
                AND ShoppingMallProductUUID = @ProductUUID
                AND Count >= @Count 
                AND IsDeleted = @IsDeleted",
                        new
                        {
                            Count = info.Count,
                            UpdateTime = DateTime.Now,
                            UpdateUserUUID = UserUUID,
                            ProductUUID = info.ProductUUID,
                            UUID = info.SpecificationUUID,
                            IsDeleted = Status.Disable
                        }
                    );
                    if (rowsAffected == 0)
                    {
                        await db.RollbackTranAsync();
                        return Error("库存不足或商品已下架");
                    }
                    // 获取最新商品信息用于计算金额
                    var hsps = await db.Queryable<ShoppingMallProductSpecification>()
                                .Where(s => s.UUID == info.SpecificationUUID)
                                .FirstAsync();

                    decimal orderAmount;
                    Guid hsouuid = Guid.NewGuid();
                    // 拼团订单
                    if (info.JoinGroup == Status.Enable)
                    {
                        ShoppingMallProductGroupParticipant ckhspgp = ProductGroup(info, hsouuid);
                        orderAmount = (hsps.GroupPrice != 0 ? hsps.GroupPrice : hsps.Price) * info.Count;
                    }
                    else
                    {
                        orderAmount = hsps.Price * info.Count;
                    }
                    // --------- 优惠----------//
                    decimal discountAmount = 0; // 优惠逻辑未实现
                                                // --------- 优惠----------//


                    // 创建订单
                    ShoppingMallOrder hso = new()
                    {
                        UUID = hsouuid,
                        ShoppingMallOrderTotalUUID = orderTotal.UUID,
                        ShoppingMallProductUUID = info.ProductUUID,
                        ShoppingMallProductSpecificationUUID = info.SpecificationUUID,
                        Count = info.Count,
                        OrderAmount = orderAmount,
                        DiscountAmount = discountAmount,
                        Address = da.GetFullAddress(),
                        ContactPerson = da.ContactPerson,
                        ContactPhone = da.ContactPhone,
                        Remark = info.Remark,
                        CreateUserUUID = UserUUID,
                        CreateTime = DateTime.Now,
                        IsGroup = info.JoinGroup,
                    };

                    hso = await db.Insertable(hso).ExecuteReturnEntityAsync();

                    orderTotal.OrderAmount += hso.OrderAmount;

                    // 关联图片
                    foreach (string url in info.ImageUrls)
                    {
                        Attachment temp = new Attachment()
                        {
                            BusinessId = hso.UUID,
                            Url = url,
                            CreatedBy = UserUUID
                        };
                        await db.Insertable(temp).ExecuteCommandAsync();
                    }
                }

                // 更新订单总金额
                await db.Updateable(orderTotal).ExecuteCommandAsync();

                await db.CommitTranAsync();
                return Success(orderTotal);
            }
            catch (MSGException ex)
            {
                await db.RollbackTranAsync();
                return Error(ex.Message);
            }
            catch (Exception ex)
            {
                await db.RollbackTranAsync();
                return Error("提交订单失败，请稍后重试。");
            }
        }

        /// <summary>
        /// 拼团
        /// </summary>
        /// <param name="info"></param>
        /// <param name="hsouuid"></param>
        /// <returns></returns>
        /// <exception cref="MSGException"></exception>
        private ShoppingMallProductGroupParticipant ProductGroup(ShoppingMallSubmitOrderInfo info, Guid hsouuid)
        {
            // 查找拼团活动
            ShoppingMallProductGroupActivity hspga = db.Queryable<ShoppingMallProductGroupActivity>()
                .Where(hspga => hspga.IsDeleted == Status.Disable)
                .Where(hspga => hspga.Status == Status.Enable)
                .Where(hspga => hspga.EndTime > DateTime.Now)
                .First() ?? throw new MSGException("没有正在进行的拼团活动")
                ;

            // 检查拼团活动是否已满
            List<ShoppingMallProductGroupParticipant> ckhspgp = db.Queryable<ShoppingMallProductGroupParticipant>()
                .Where(hspgp => hspgp.ShoppingMallProductGroupActivityUUID == hspga.UUID)
                .Where(hspgp => hspgp.Status == GroupParticipantStatus.PendingPayment ||
                    hspgp.Status == GroupParticipantStatus.Paid ||
                    hspgp.Status == GroupParticipantStatus.GroupSuccess ||
                    hspgp.Status == GroupParticipantStatus.Completed)
                .Where(hspgp => hspgp.ExpireTime > DateTime.Now)
                //.Where(hspgp => hspgp.GroupDate == info.ServiceDate.Date)
                .ToList()
                ;
            if (ckhspgp.Count + info.Count > hspga.MaxGroupCount)
            {
                throw new MSGException("已达到拼团上限");
            }


            ShoppingMallProductGroupParticipant hspgp = new()
            {
                ShoppingMallProductGroupActivityUUID = hspga.UUID,
                UserUUID = UserUUID,
                ExpireTime = hspga.EndTime,
                ShoppingMallOrderUUID = hsouuid,
                ShoppingMallProductUUID = info.ProductUUID,
                CreateTime = DateTime.Now,
                CreateUserUUID = UserUUID
            };
            return db.Insertable(hspgp).ExecuteReturnEntity();
        }

        /// <summary>
        /// 订单付款
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel> OrderPayment(Guid OrderTotalUUID, PayWay way)
        {
            try
            {
                await db.BeginTranAsync();
                var orders = await db.Queryable<ShoppingMallOrderTotal, ShoppingMallOrder>((smot, smo) => new JoinQueryInfos(
                        JoinType.Left, smot.UUID == smo.ShoppingMallOrderTotalUUID
                    ))
                    .Where(smot => smot.IsDeleted == Status.Disable)
                    .Where(smot => smot.ExpireTime > DateTime.Now)
                    .Where(smot => smot.OrderStatus == ShoppingMallOrderStatus.PendingPayment)
                    .Where((smot, smo) => smo.IsDeleted == Status.Disable)
                    .Where((smot, smo) => smo.OrderStatus == ShoppingMallOrderStatus.PendingPayment)
                    .Where(smot => smot.UUID == OrderTotalUUID)
                    .Select((smot, smo) => new
                    {
                        smot,
                        smo
                    }).ToListAsync();


                if (orders.Count == 0)
                {
                    return Error("未找到待支付的订单");
                }

                foreach (var order in orders)
                {
                    //_paymentCenterService.CreateBill(Guid.NewGuid(),BusinessType.HomeServicePay, way,)

                    //未实现付款逻辑，假设付款成功
                    order.smo.OrderStatus = ShoppingMallOrderStatus.Completed;
                    order.smo.PayAmount = order.smo.OrderAmount; // 假设全额付款
                    order.smo.UpdateTime = DateTime.Now;
                    order.smo.UpdateUserUUID = UserUUID;

                    // 更新订单状态和付款金额
                    await db.Updateable(order.smo).ExecuteCommandAsync();

                    if (order.smo.IsGroup == Status.Enable)
                    {
                        ShoppingMallProductGroupParticipant hspgp = await db.Queryable<ShoppingMallProductGroupParticipant>()
                            .Where(hspgp => hspgp.UserUUID == UserUUID)
                            .Where(hspgp => hspgp.ShoppingMallOrderUUID == order.smo.UUID)
                            .FirstAsync()
                            ;

                        hspgp.Status = GroupParticipantStatus.Paid;
                        hspgp.ExpireTime = null; // 取消过期时间

                        // 更新拼团参与者状态
                        await db.Updateable(hspgp).ExecuteCommandAsync();
                    }
                }

                orders[0].smot.PayAmount = orders[0].smot.OrderAmount;
                orders[0].smot.OrderStatus = ShoppingMallOrderStatus.Completed;
                orders[0].smot.UpdateTime = DateTime.Now;
                orders[0].smot.UpdateUserUUID = UserUUID;
                orders[0].smot.ExpireTime = null; // 取消过期时间

                // 更新订单总金额和状态
                await db.Updateable(orders[0].smot).ExecuteCommandAsync();


                await db.CommitTranAsync();
                return Success("付款成功，逻辑未实现，现在默认成功");
            }
            catch (Exception)
            {
                await db.RollbackTranAsync();
                return Error("付款失败，请稍后重试。");
            }
        }

        /// <summary>
        /// 获取商城订单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetOrder(GetOrderInfo info)
        {
            int total = 0;

            var data = db.Queryable<ShoppingMallOrderTotal>()
                    .Where(smot => smot.IsDeleted == Status.Disable)
                    .Where(smot => smot.CreateUserUUID == UserUUID)
                    .WhereIF(info.OrderStatus.HasValue, smot => smot.OrderStatus == info.OrderStatus)
                    .WhereIF(info.OrderTotalUUID.HasValue, smot => smot.UUID == info.OrderTotalUUID)
                    .ToPageList(info.PageNumber, info.PageSize, ref total)
                    ;

            List<Guid> uuids = data.Select(x => x.UUID).ToList();

            List<ShoppingMallOrder> orders = db.Queryable<ShoppingMallOrder>()
                .Where(smo => uuids.Contains(smo.ShoppingMallOrderTotalUUID))
                .Where(smo => smo.IsDeleted == Status.Disable)
                .Where(smo => smo.CreateUserUUID == UserUUID)
                .WhereIF(info.OrderStatus.HasValue, smp => smp.OrderStatus == info.OrderStatus)
                .WhereIF(info.OrderUUID.HasValue, smot => smot.UUID == info.OrderUUID)
                .ToList()
                ;
            List<Guid> productuuids = orders.Select(x => x.ShoppingMallProductUUID).ToList();
            List<Guid> specificationuuids = orders.Select(x => x.ShoppingMallProductSpecificationUUID).ToList();

            List<ShoppingMallProduct> products = db.Queryable<ShoppingMallProduct>()
                .Where(smp => productuuids.Contains(smp.UUID))
                .ToList()
                ;

            List<Guid> storesuuids = products.Select(x => x.ShoppingMallStoreUUID).ToList();

            List<ShoppingMallProductSpecification> specifications = db.Queryable<ShoppingMallProductSpecification>()
                .Where(smp => specificationuuids.Contains(smp.UUID))
                .ToList()
                ;

            List<ShoppingMallStore> stores = db.Queryable<ShoppingMallStore>()
                .Where(sms => storesuuids.Contains(sms.UUID))
                .ToList()
                ;

            foreach (var item in data)
            {
                item.Orders = [.. orders.Where(x => x.ShoppingMallOrderTotalUUID == item.UUID)];
                foreach (var order in item.Orders)
                {
                    order.Product = products.Where(x => x.UUID == order.ShoppingMallProductUUID).First();
                    order.ProductSpecification = specifications.Where(x => x.UUID == order.ShoppingMallProductSpecificationUUID).First();
                    if (order.Product != null)
                    {
                        order.Store = stores.Where(x => x.UUID == order.Product.ShoppingMallStoreUUID).First();
                    }

                }
            }

            return PageSuccess(info.PageNumber, info.PageSize, total, data);
        }

        /// <summary>
        /// 获取商品已完成的订单列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetProductOrders(GetProductOrdersInfo info)
        {
            int total = 0;


            var data = db.Queryable<ShoppingMallOrder, Customer, ShoppingMallProduct>((smo, u, smp) => new JoinQueryInfos(
                    JoinType.Left, smo.CreateUserUUID == u.UUID,
                    JoinType.Left, smo.ShoppingMallProductUUID == smp.UUID
                ))
                //.Where(smo => uuids.Contains(smo.ShoppingMallOrderTotalUUID))
                .Where(smo => smo.ShoppingMallProductUUID == info.ProductUUID)
                .Where(smo => smo.IsDeleted == Status.Disable)
                .Where(smo => smo.OrderStatus == ShoppingMallOrderStatus.Completed
                    || smo.OrderStatus == ShoppingMallOrderStatus.IsComment
                    || smo.OrderStatus == ShoppingMallOrderStatus.Paid
                 )
                .WhereIF(info.IsGroup.HasValue, smo => smo.IsGroup == info.IsGroup)
                .OrderBy(smo => smo.CreateTime, OrderByType.Desc)
                .Select((smo, u, smp) => new
                {
                    AvatarUrl = u.PicUrl,
                    DisplayName = u.Name,
                    smp.Title,
                    smo.Count,
                    smo.CreateTime
                })
                .ToPageList(info.PageNumber, info.PageSize, ref total)
                ;

            return PageSuccess(info.PageNumber, info.PageSize, total, data);
        }

        /// <summary>
        /// 评论完成的订单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> SubmitOrderComment(ShoppingMallSubmitOrderComment info)
        {
            try
            {
                await db.BeginTranAsync();

                ShoppingMallOrder ckhso = await db.Queryable<ShoppingMallOrder>()
                    .Where(hso => hso.IsDeleted == Status.Disable)
                    .Where(hso => hso.UUID == info.OrderUUID)
                    .Where(hso => hso.OrderStatus == ShoppingMallOrderStatus.Completed)
                    .FirstAsync()
                    ;

                if (ckhso == null)
                {
                    return Error("订单不存在或未完成或已评论");
                }
                ckhso.OrderStatus = ShoppingMallOrderStatus.IsComment;
                ckhso.UpdateTime = DateTime.Now;
                ckhso.UpdateUserUUID = UserUUID;
                await db.Updateable(ckhso).ExecuteCommandAsync();

                //ShoppingMallOrderComment ckhsoc = await db.Queryable<ShoppingMallOrderComment>()
                //    .Where(hsoc => hsoc.ShoppingMallOrderUUID == info.OrderUUID && hsoc.IsDeleted == Status.Disable)
                //    .FirstAsync()
                //    ;
                //if (ckhsoc != null)
                //{
                //    return Error("订单已评论，请勿重复评论");
                //}

                ShoppingMallOrderComment hsoc = new()
                {
                    ShoppingMallOrderUUID = info.OrderUUID,
                    ShoppingMallProductUUID = ckhso.ShoppingMallProductUUID, // 关联的商品UUID
                    UserUUID = UserUUID,
                    UserName = UserName,
                    StarRating = info.StarRating, // 默认五星
                    Content = info.Text,
                    CreateTime = DateTime.Now
                };
                ShoppingMallOrderComment rehsoc = await db.Insertable(hsoc).ExecuteReturnEntityAsync();

                foreach (var url in info.Urls)
                {
                    Attachment ac = new()
                    {
                        BusinessId = rehsoc.UUID,
                        Url = url,
                        CreatedAt = DateTime.Now,
                        CreatedBy = UserUUID
                    };
                    await db.Insertable(ac).ExecuteCommandAsync();
                }

                //判断主订单下面还有没有其他其他订单，如果没有将主订单状态同步修改

                await db.CommitTranAsync();
                return Success("评论成功");
            }
            catch (Exception)
            {
                await db.RollbackTranAsync();
                return Error("评论失败");
            }
        }

        /// <summary>
        /// 获取我的订单评论
        /// </summary>
        /// <param name="OrderUUID"></param>
        /// <returns></returns>
        public ResponseModel GetOrderComment(GetOrderCommentInfo info)
        {
            int total = 0;
            var query = db.Queryable<ShoppingMallOrderComment>()
                .Where(smoc => smoc.IsDeleted == Status.Disable)
                .Where(smoc => smoc.ShoppingMallProductUUID == info.ProductUUID)
                .WhereIF(info.OrderUUID.HasValue, smoc => smoc.ShoppingMallOrderUUID == info.OrderUUID)
                .WhereIF(info.UserUUID.HasValue, smoc => smoc.UserUUID == UserUUID)
                .Where(smoc => info.sr.Contains(smoc.StarRating))

                ;

            // 图片筛选
            if (info.FilterImages == Status.Enable)
            {
                query = query.Where(hsoc => db.Queryable<Attachment>()
                    .Where(a => a.BusinessId == hsoc.UUID && a.Status == Status.Enable)
                    .Count() > 0);
            }

            var res = query.Select(smoc => new GetOrderCommentDto
            {
                UUID = smoc.UUID,
                StarRating = smoc.StarRating,
                UserName = smoc.UserName,
                Content = smoc.Content,
                CreateTime = smoc.CreateTime,
                CreateUserUUID = smoc.UserUUID
            })
                .ToPageList(info.PageNumber, info.PageSize, ref total);

            List<Guid> uuids = [.. res.Select(x => x.CreateUserUUID)];

            List<User> Users = db.Queryable<User>().Where(u => uuids.Contains(u.UUID)).ToList();

            foreach (var item in res)
            {
                item.Urls = GetAttachment(item.UUID);
                item.AvatarUrl = Users.Where(x => x.UUID == item.CreateUserUUID).Select(x => x.AvatarUrl).FirstOrDefault();
            }

            return PageSuccess(info.PageNumber, info.PageSize, total, res);
        }
    }
}
